package zxing.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.virtualapp.R;
import io.virtualapp.abs.ui.VActivity;
import io.virtualapp.bean.MakeBean;
import io.virtualapp.mylibrary.callback.BaseCallback;
import io.virtualapp.mylibrary.util.HttpUtils;
import io.virtualapp.mylibrary.util.ToastUtils;
import okhttp3.Request;
import okhttp3.Response;
import zxing.activity.bean.LoveBean;
import zxing.activity.bean.VoiceFileBean;
import zxing.activity.utils.AudioRecoderUtils;
import zxing.activity.utils.RecordView;


public class Record1Activity extends VActivity implements View.OnTouchListener, View.OnClickListener, MediaPlayer.OnCompletionListener {

    private RecordView mRecorfView;
    private AudioRecoderUtils mAudioRecoderUtils;
    private MediaPlayer mediaPlayer;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int db = (int) (Math.random() * 100);
            mRecorfView.setVolume(db);

        }
    };
    private List<VoiceFileBean> beans;
    //申请录音权限
    private static final int GET_RECODE_AUDIO = 1;
    private static String[] PERMISSION_AUDIO = {
            Manifest.permission.RECORD_AUDIO
    };
    @BindView(R.id.head_back)
    ImageView head_back;
    @BindView(R.id.head_center_title)
    TextView head_center_title;
    @BindView(R.id.mTextView)
    TextView mTextView;
    @BindView(R.id.button_clear)
    Button button_clear;
    @BindView(R.id.button_play)
    Button button_play;
    @BindView(R.id.head_right_title)
    TextView head_right_title;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record);
        ButterKnife.bind(this);
//          申请录音权限
        int permission = ActivityCompat.checkSelfPermission(Record1Activity.this,
                Manifest.permission.RECORD_AUDIO);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(Record1Activity.this, PERMISSION_AUDIO,
                    GET_RECODE_AUDIO);
        }
        mAudioRecoderUtils = new AudioRecoderUtils();
        Button button = findViewById(R.id.button);
        button.setOnTouchListener(this);
        beans = new ArrayList<>();
        if (beans.size() > 0) {
            beans.clear();
        }
        head_right_title.setVisibility(View.VISIBLE);
        head_right_title.setText("生成二维码");
        mRecorfView = findViewById(R.id.recordView);
        mRecorfView.setCountdownTime(60);
        mRecorfView.setModel(RecordView.MODEL_RECORD);
        head_center_title.setText("录音二维码");
        head_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initDatas();
    }


    private boolean isPlay = true;


    protected void initDatas() {

        button_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (beans.size() > 0) {
                    if (isPlay == true) {
                        isPlay = false;
                        mediaPlayerStart(beans.get(0).getFilePath());
                        button_play.setBackground(mContext.getResources().getDrawable(R.mipmap.zanting_play));
                    } else {
                        isPlay = true;
                        mediaPlayerStop();
                        button_play.setBackground(mContext.getResources().getDrawable(R.mipmap.bofang));
                    }
                } else
                    Toast.makeText(Record1Activity.this, "暂无录音，请先录音", Toast.LENGTH_SHORT).show();
            }

        });
        button_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (beans.size() > 0) {
                    showistimeexpirseAlerDialog();
                } else {
                    Toast.makeText(Record1Activity.this, "暂无录音，请先录音", Toast.LENGTH_SHORT).show();
                }
            }
        });
        head_right_title.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onClick(View v) {
                if (beans.size() > 0) {
                    try {
                        UpLoadService(fileToString(beans.get(0).getFilePath()), beans.get(0).getFileName());
//                        saveToFile(fileToString(beans.get(0).getFilePath()),getContext()    );

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(Record1Activity.this, "暂无录音，请先录音", Toast.LENGTH_SHORT).show();
                }

            }
        });
        //录音回调
        mAudioRecoderUtils.setOnAudioStatusUpdateListener(new AudioRecoderUtils.OnAudioStatusUpdateListener() {
            //录音中....db为声音分贝，time为录音时长
            @Override
            public void onUpdate(double db, long time) {
//                mImageView.getDrawable().setLevel((int) (3000 + 6000 * db / 100));
//                mTextView.setText(TimeUtils.long2String(time));
            }

            //录音结束，filePath为保存路径
            @Override
            public void onStop(String filePath) {
                Toast.makeText(Record1Activity.this, "录音保存成功" + filePath, Toast.LENGTH_SHORT).show();
                File file = new File(filePath);
                VoiceFileBean bean = new VoiceFileBean();
                // 获取扩展名
                String FileEnd = file.getName().substring(file.getName().lastIndexOf(".") + 1, file.getName().length()).toLowerCase();
                if (FileEnd.equals("aac")) {
                    bean.setFileName(file.getName());
                    ///storage/emulated/0/record/20181126114528.aac"/storage/emulated/0/record/lol.mp3"
                    bean.setFilePath(file.getPath());
                    beans.add(bean);
                }
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static String fileToString(String path) throws Exception {
        String base64 = null;
        InputStream in = null;
        try {
            File file = new File(path);
            in = new FileInputStream(file);
            byte[] bytes = new byte[(int) file.length()];
            in.read(bytes);
            base64 = Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64;

    }

    /*base64 转文件*/
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void saveToFile(String base64, Context context) {
        BufferedWriter out = null;

        //获取SD卡状态
        String state = Environment.getExternalStorageDirectory().getPath();
        File file = null;
        //创建文件目录
        String filePath = state + File.separator + "erweima";
        File dir = new File(filePath);
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdirs();
        }
        BufferedOutputStream bos = null;
        java.io.FileOutputStream fos = null;
        try {
            byte[] bytes = Base64.getDecoder().decode(base64);
            file = new File(filePath + File.separator + "teqwedasdt.mp3");
            fos = new java.io.FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    //转base64
//    @SuppressLint("WrongConstant")
//    private String encodeBase64File(String path) throws Exception {
//         File file = new File(path);
//        FileInputStream inputFile = new FileInputStream(file);
//        byte[] buffer = new byte[(int) file.length()];
//        inputFile.read(buffer);
//        inputFile.close();
//        String date = Base64.encodeToString(buffer, Base64.DEFAULT);
//        return null;
//    }

    /**
     * 文件转Base64.
     *
     * @param filePath
     * @return
     */
    public static String file2Base64(String filePath) {
       /* FileInputStream objFileIS = null;
        try {
            objFileIS = new FileInputStream(filePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        ByteArrayOutputStream objByteArrayOS = new ByteArrayOutputStream();
        byte[] byteBufferString = new byte[1024];
        try {
            for (int readNum; (readNum = objFileIS.read(byteBufferString)) != -1; ) {
                objByteArrayOS.write(byteBufferString, 0, readNum);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        String videodata = Base64.encodeToString(objByteArrayOS.toByteArray(), Base64.DEFAULT);*/
        return null;
    }

    private TimerTask timeTask;
    private Timer timeTimer = new Timer(true);

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            mRecorfView.start();
            mAudioRecoderUtils.startRecord();
            mTextView.setVisibility(View.VISIBLE);
            timeTimer.schedule(timeTask = new TimerTask() {
                public void run() {
                    Message msg = new Message();
                    msg.what = 1;
                    handler.sendMessage(msg);

                }
            }, 20, 20);
            mRecorfView.setOnCountDownListener(new RecordView.OnCountDownListener() {
                @Override
                public void onCountDown() {

                    mAudioRecoderUtils.stopRecord();
                    mTextView.setVisibility(View.GONE);
                }
            });
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            mRecorfView.cancel();
        }
        return false;
    }

    private void showistimeexpirseAlerDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("重新录制");
        builder.setMessage("是否删除当前录音，重新录制？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                beans.clear();
                mRecorfView.setCountdownTime(60);
                mRecorfView.setModel(RecordView.MODEL_RECORD);
                isPlay = true;
                mediaPlayerStop();
                button_play.setBackground(mContext.getResources().getDrawable(R.mipmap.bofang));
                Toast.makeText(Record1Activity.this, "删除成功", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.show();
    }

    @Override
    public void onClick(View v) {
    }


    /**
     * 播放音频文件
     */
    private void mediaPlayerStart(String voiceFilePath) {
        mediaPlayer = MediaPlayer.create(this, Uri.parse(voiceFilePath));
        mediaPlayer.setOnCompletionListener(this);
        if (!mediaPlayer.isPlaying()) {
            mediaPlayer.start();
        }
    }

    /**
     * 取消播放音频文件
     */
    private void mediaPlayerStop() {
        if (mediaPlayer.isPlaying() || mediaPlayer != null) {
            mediaPlayer.stop();
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        mp.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            try {
                mediaPlayer.release();
                mediaPlayer.stop();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void UpLoadService(String sound, String filename) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpUtils.getInstance().addSound(
                        sound + "",
                        "lol.mp3" + "",

                        new BaseCallback<LoveBean>() {
                            @Override
                            public void onRequestBefore() {
                            }

                            @Override
                            public void onFailure(Request request, Exception e) {
                                new Handler(getMainLooper()).post(new Runnable() {
                                    @Override
                                    public void run() {
                                        ToastUtils.showShortToast("提交失败" + e.toString());
                                    }
                                });
                            }

                            @Override
                            public void onSuccess(Response response, LoveBean o) {
                                if (o != null && o.isIssucc()) {
                                    ToastUtils.showShortToast("提交成功");
                                    Record1Activity.this.setResult(RESULT_OK);
                                    String url = o.getData() + "";
                                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
                                    Date date = new Date(System.currentTimeMillis());
                                    String n = simpleDateFormat.format(date);
                                    MakeBean user = new MakeBean();
                                    user.setName(n);
                                    user.setTit(url + "");
                                    user.save();
                                    Intent intent = new Intent(getActivity(), CodeDisplayActivity.class);
                                    intent.putExtra("data", url);
                                    intent.putExtra("title", "录音二维码");
                                    startActivity(intent);
                                } else {
                                    new Handler(getMainLooper()).post(new Runnable() {
                                        @Override
                                        public void run() {
                                            ToastUtils.showShortToast("提交失败" + o.getMsg());
                                        }
                                    });
                                }

                            }

                            @Override
                            public void onError(Response response, int errorCode, Exception e) {
                                new Handler(getMainLooper()).post(new Runnable() {
                                    @Override
                                    public void run() {
                                        ToastUtils.showShortToast("提交失败" + e.toString());
                                    }
                                });
                            }
                        });

            }
        }).

                start();

    }


}
